import React, { useEffect, useMemo, useRef } from 'react';
import { client } from 'mp-package-base';

const loaders = {};

export default function OnlyOfficeViewer({ host = '', config = {} }) {
  const editor = useRef();
  const id = useMemo(() => Math.random(), []);

  if (!loaders[host]) loaders[host] = window.MP.load([host + '/web-apps/apps/api/documents/api.js']);

  useEffect(() => {
    loaders[host].then(() => {
      client.job('Office.GetOnlyOfficeToken', { payload: config }).then(token => {
        editor.current = new window.DocsAPI.DocEditor(id, { token, ...config });
      });
    });
    // eslint-disable-next-line
  }, []);

  return <div id={id}></div>;
}